<!--
*Author：
 *Contact：
 *代码由框架生成,任何更改都可能导致被代码生成器覆盖
 *业务请在@/extension/system/workbusiness/PROJ_KitCheck.js此处编写
 -->
<template>
    <view-grid ref="grid"
               :columns="columns"
               :detail="detail"
               :editFormFields="editFormFields"
               :editFormOptions="editFormOptions"
               :searchFormFields="searchFormFields"
               :searchFormOptions="searchFormOptions"
               :table="table"
               :extend="extend">
    </view-grid>
</template>
<script>

    import extend from "@/extension/system/workbusiness/PROJ_KitCheck.js";
    import { ref, defineComponent } from "vue";
    export default defineComponent({
        setup() {
            const table = ref({
                key: 'PROJKitCheck_Id',
                footer: "Foots",
                cnName: '齐套检查',
                name: 'workbusiness/PROJ_KitCheck',
                url: "/PROJ_KitCheck/",
                sortName: "CreateOn"
            });
            const editFormFields = ref({"TaskTitle":"","RequiredTool":"","RequiredMaterial":""});
            const editFormOptions = ref([[{"title":"任务名称","required":true,"field":"TaskTitle","type":"text"},
                               {"title":"所需工具","field":"RequiredTool","type":"text"},
                               {"title":"所需材料","field":"RequiredMaterial","type":"text"}]]);
            const searchFormFields = ref({});
            const searchFormOptions = ref([]);
            const columns = ref([{field:'PROJKitCheck_Id',title:'PROJKitCheck_Id',type:'guid',width:110,hidden:true,readonly:true,require:true,align:'left'},
                       {field:'TaskTitle',title:'任务名称',type:'string',link:true,width:110,require:true,align:'left',sort:true},
//                        {
//   field: 'RequiredTool',
//   title: '所需工具',
//   width: 110,
//   render: (h, { row }) => {
//     debugger;
//     // 获取父组件实例（假设已通过作用域传递）
//     const vm = globalVM
    
//     // 初始化检查Status
//     if (!row.Status) {
//       vm.$set(row, 'Status', {})
//     }

//     return (
//       <div>
//         {row.RequiredTool.split(',').map((tool, index) => {
//           const toolName = tool.trim()
          
//           // 初始化单个工具状态
//           if (!row._toolStates[toolName]) {
//             vm.$set(row._toolStates, toolName, 'danger')
//           }

//           return (
//             <el-button
//               key={index}
//               size="small"
//               type={row._toolStates[toolName]}
//               style="margin-right:5px"
//               onClick={() => {
//                 const newState = row._toolStates[toolName] === 'danger'
//                   ? 'success'
//                   : 'danger'
//                 vm.$set(row._toolStates, toolName, newState)
//               }}
//             >
//               {toolName}
//             </el-button>
//           )
//         })}
//       </div>
//     )
//   }
// }  ,
    //                   {field:'RequiredTool',title:'所需工具',type:'string',width:110,align:'left',// 使用 render 函数代替模板
    //                    render: (h, { row, column, index }) => {
    //                     let requiredTools = row.requiredTools;//row.RequiredTool.split(',');
    //                     let state=0;
    //                      // 初始化当前工具状态
    //                   let newType='danger';
    //                  // 初始化状态存储（需要Vue响应式系统支持）
 
    //       return (
            
    //         <div>             
            
    //         {

    //             requiredTools.map((tool, index) => (

    //             <el-tag
    //           key={tool}
    //           size="small"
    //           type= {state === 1 ? 'success' : 'danger'}//"info"
    //           effect="dark"
    //             onClick={($e) => {
    //                 // 这里可以添加点击事件
    //                  // 切换状态
    //                newType =state === 1 
    //                 ? 'danger' 
    //                 : 'success'
                
    //                 state = state === 1 ? 0 : 1;
    //                 alert(newType);
    //             }}
    //           style="margin-right:5px"
    //         >
    //         <span style="color: {state === 1 ? green : red};">{tool}</span>
          
    //         </el-tag>

    //             ))

    //         }
           
            
    //     </div>
    //     );
    // }
    //                 },
    {
  field: 'RequiredTool',
  title: '所需工具',
  type: 'array',
  width: 150,
  align: 'left',
  render: (h, { row }) => {
    if (!row.requiredTools?.length) return h('span', 'N/A');
    const stateMap = row.toolsStatus || {}; // 假设在组件data中定义了 materialsStatus: {}
    // 事件处理器
    const handleClick = (kit,type,item) => {
   //   console.log('点击材料:', item);
    
      // 这里可以触发 Vue 组件中的方法
    //  this.handleMaterialClick(item); // 需要确保 this 上下文正确
    debugger;
   
    const index = 0;//row.findIndex(k => k.id === kit.id)
  if (index !== -1) {
    if (type === 'tool') {
        stateMap[item]=!stateMap[item]
        // row.toolsStatus[item] = !row.toolsStatus[item] 
    
    } else {
        stateMap[item]=!stateMap[item]
        // row.toolsStatus[item] = !row.toolsStatus[item] 
     
    }
    const allToolsReady =Object.values(stateMap).every(status => status);
   const allMaterialsReady = Object.values(row.materialsStatus).every(status => status);
   row.Status = (allToolsReady && allMaterialsReady) ? '已齐套' : '未齐套'
    
   
  }

    };

    return h('div', {
      class: 'material-list',
      style: { lineHeight: '1.5em',cursor: 'pointer' }
    }, [
      row.requiredTools.map(item => 
      <el-tag
              key={item}
              size="small"
              type= {stateMap[item] ? 'success' : 'danger'}//"info"
              effect="dark"
                onClick={($e) => {   
                   handleClick(row,'item',item); // 触发点击事件
                }}
              style="margin-right:5px"
            >
            <span >{item}</span>
          
            </el-tag>
      )
    ]);
  }
},
    //                 {field:'RequiredMaterial',title:'所需材料',type:'string',width:110,align:'left',// 使用 render 函数代替模板
    //                    render: (h, { row, column, index }) => {
                   

    //       return (
            
    //         <template   #default="scope">
    //             <span>sss</span>
    //             </template>
    //     );
    // }
    //                 },
    
//     {
//   field: 'RequiredMaterial',
//   title: '所需材料',
//   type: 'array',
//   width: 150,
//   align: 'left',
//   render: (h, { row }) => {
//     // 空值处理
//     if (!row.requiredMaterials?.length) return h('span', 'N/A');

//     // 循环渲染数组元素
//     return h('div', {
//       class: 'material-list',
//       style: { lineHeight: '1.5em' }
//     }, [
//       row.requiredMaterials.map(item => 
//         h('div', { 
//           class: 'material-item',
//           style: { margin: '2px 0', paddingLeft: '8px' }
//         }, `• ${item}`)
//       )
//     ]);
//   }
// },
{
  field: 'RequiredMaterial',
  title: '所需材料',
  type: 'array',
  width: 150,
  align: 'left',
  render: (h, { row }) => {
    if (!row.requiredMaterials?.length) return h('span', 'N/A');
    const stateMap = row.materialsStatus || {}; // 假设在组件data中定义了 materialsStatus: {}
    // 事件处理器
    const handleClick = (kit,type,item) => {
   //   console.log('点击材料:', item);
    
      // 这里可以触发 Vue 组件中的方法
    //  this.handleMaterialClick(item); // 需要确保 this 上下文正确
    debugger;
   
    const index = 0;//row.findIndex(k => k.id === kit.id)
  if (index !== -1) {
    if (type === 'tool') {
        stateMap[item]=!stateMap[item]
        // row.toolsStatus[item] = !row.toolsStatus[item] 
    
    } else {
        stateMap[item]=!stateMap[item]
        // row.toolsStatus[item] = !row.toolsStatus[item] 
     
    }
    debugger;
    // 检查是否全部齐套
   // const allToolsReady = Object.values(kits.value[index].toolsStatus).every(status => status)
   // const allMaterialsReady = Object.values(kits.value[index].materialsStatus).every(status => status)
   const allToolsReady =Object.values(row.toolsStatus).every(status => status);
   const allMaterialsReady = Object.values(stateMap).every(status => status);
   row.Status = (allToolsReady && allMaterialsReady) ? '已齐套' : '未齐套'
    
   
  }

    };

    return h('div', {
      class: 'material-list',
      style: { lineHeight: '1.5em',cursor: 'pointer' }
    }, [
      row.requiredMaterials.map(item => 
      <el-tag
              key={item}
              size="small"
              type= {stateMap[item] ? 'success' : 'danger'}//"info"
              effect="dark"
                onClick={($e) => {   
                   handleClick(row,'item',item); // 触发点击事件
                }}
              style="margin-right:5px"
            >
            <span >{item}</span>
          
            </el-tag>
      )
    ]);
  }
},
                
                    //    {field:'RequiredMaterial',title:'所需材料',type:'string',width:110,align:'left'},
                       {field:'CheckDate',title:'检查日期',type:'datetime',width:150,align:'left',sort:true},
                       {field:'Checker',title:'检查人',type:'string',width:110,align:'left'},
                       {field:'Description',title:'描述',type:'string',width:220,align:'left'},
                       //{field:'Status',title:'状态',type:'string',width:110,align:'left'},
                       {
  field: 'Status',
  title: '状态',
  type: 'array',
  width: 150,
  align: 'left',
  render: (h, { row }) => {
   // if (!row.Status?.length) return h('span', 'N/A');
    
 debugger;
    // 状态类型映射
const getStatusType = (status) => {
  const statusMap = {
    '未齐套': 'warning',
    '已齐套': 'success',
    '检查中': 'info'
  }
  return statusMap[status] || ''
}

    return h('div', {
      class: 'material-list',
      style: { lineHeight: '1.5em' }
    }, [
      
      <el-tag
            
              size="small"
              type= {getStatusType(row.Status)}//"info"
              effect="dark"              
              style="margin-right:5px"
            >
            <span >{row.Status}</span>
          
            </el-tag>
      
    ]);
  }
},
                       {field:'CreateBy',title:'创建人',type:'string',width:110,hidden:true,align:'left'},
                       {field:'CreateOn',title:'创建时间',type:'datetime',width:150,hidden:true,align:'left',sort:true},
                       {field:'UpdateBy',title:'更新人',type:'string',width:110,hidden:true,align:'left'},
                       {field:'LastUpdateOn',title:'更新时间',type:'datetime',width:150,hidden:true,align:'left',sort:true},
                       {field:'IsDeleted',title:'逻辑删除 0/不删除 1/已删除',type:'bool',width:110,hidden:true,align:'left'}]);
            const detail = ref({
                cnName: "#detailCnName",
                table: "#detailTable",
                columns: [],
                sortName: "",
                key: ""
            });
            return {
                table,
                extend,
                editFormFields,
                editFormOptions,
                searchFormFields,
                searchFormOptions,
                columns,
                detail,
            };
        },
    });
</script>
<style scoped>
.el-tag {
  pointer-events: none;
  position: relative;
  z-index: -1;
}
</style>
